package com.weilele.mvvm.base.helper

import android.app.Activity
import android.content.ContextWrapper
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LiveData
import androidx.lifecycle.Observer
import com.weilele.mvvm.utils.safeGet

inline fun <T> LifecycleOwner.observerLiveData(
        liveData: LiveData<T>,
        crossinline call: (T) -> Unit
): Observer<T> {
    val observer = Observer<T> {
        call.invoke(it)
    }
    liveData.observe(this, observer)
    return observer
}

inline fun <T> LifecycleOwner.observerLiveDataSuccess(
        liveData: LiveData<StatusValue<T>>,
        crossinline call: (T) -> Unit
): Observer<StatusValue<T>> {
    val observer = Observer<StatusValue<T>> {
        val value = liveData.value
        if (value is StatusValue.Success) {
            call.invoke(value.nonNullValue)
        }
    }
    liveData.observe(this, observer)
    return observer
}

inline fun <T> LiveData<T>.observeForeverLiveData(
        crossinline call: (T) -> Unit
): Observer<T> {
    val observer = Observer<T> {
        call.invoke(it)
    }
    this.observeForever(observer)
    return observer
}

inline fun <T> LiveData<StatusValue<T>>.observerForeverLiveDataSuccess(
        crossinline call: (T) -> Unit
): Observer<StatusValue<T>> {
    val observer = Observer<StatusValue<T>> {
        val value = this.value
        if (value is StatusValue.Success) {
            call.invoke(value.nonNullValue)
        }
    }
    this.observeForever(observer)
    return observer
}

//---------------------扩展属性--------------------//
val AppCompatActivity.appCompatActivity
    get() = this

val Fragment.appCompatActivity: AppCompatActivity?
    get() = activity.safeGet()
            ?: if (context is ContextWrapper && context !is Activity) (context as? ContextWrapper)?.baseContext?.safeGet() else context.safeGet()